//
//  UINavigationControllerExtension.swift
//  multimeter
//
//  Created by 强建龙 on 17/7/27.
//  Copyright © 2017年 chinake. All rights reserved.
//

import UIKit

extension UINavigationController {
    func pushViewControllerWithStoryboardID(id: String, animated: Bool, data: AnyObject!) {
        let vc = storyboard?.instantiateViewController(withIdentifier: id)
        if vc is BaseViewController || vc is BaseTableViewController {
            backetInForController(controller: vc!, data: data)
        }
        pushViewController(vc!, animated: animated)
    }
    
    func popViewControllerAnimated(animated: Bool, data: AnyObject!) -> UIViewController? {
        let count = self.viewControllers.count
        if count > 1 {
            let vc = viewControllers[count - 2]
            if vc is BaseViewController || vc is BaseTableViewController {
                backetInForController(controller: vc, data: data)
            }
        }
        return popViewController(animated: animated)
    }
    
    func popToViewControllerWithClass(_ cls: AnyClass,
                                      animated: Bool, data: NSDictionary!) -> [AnyObject]? {
        // 查找相关的ViewController
        var vc: UIViewController!
        for controller in viewControllers {
            if controller.classForCoder === cls {
                vc = controller
                break
            }
        }
        
        // 出栈 & 相关数据暂存
        if vc != nil {
            if vc is BaseViewController || vc is BaseTableViewController {
                backetInForController(controller: vc, data: data)
            }
            return popToViewController(vc, animated: animated)
        } else {
            return nil
        }
    }
    
    func popToRootViewControllerAnimated(animated: Bool, data: AnyObject!) -> [AnyObject]? {
        let vc = viewControllers[0]
        if vc is BaseViewController || vc is BaseTableViewController {
            backetInForController(controller: vc, data: data)
        }
        return popToRootViewController(animated: animated)
    }
    
    // MARK: - Internal
    fileprivate func backetInForController(controller: UIViewController, data: AnyObject!) {
        if data != nil {
            let name = NSStringFromClass(controller.classForCoder)
            let key = "__\(name)"
            Bucket.defaultBucket().bucketIn(key, value: data)
        }
    }
}
